﻿using Microsoft.AspNetCore.Mvc;
using ERP.ERPSystem.ProductionSystem;
using ERP.ERPSystem.ProductionSystem.Dto;
using ERP.Team.ProductionSystem;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;

namespace ERP.Web.Controllers.ProductionSystem
{
    /// <summary>
    /// 生产系统-生产管理-生产领料
    /// </summary>
    public class ProductionpickingController : Controller
    {
        private readonly IProductionpickingService _productionpickingService;

        public ProductionpickingController(IProductionpickingService productionpickingService)
        {
            _productionpickingService = productionpickingService;
        }

        /// <summary>
        /// 生产领料查询页面
        /// </summary>
        /// <returns></returns>
        public IActionResult ProductionpickingQuery()
        {
            return View();
        }

        /// <summary>
        /// 修改生产领料单页面
        /// </summary>
        /// <param name="id">领料单ID</param>
        /// <returns></returns>
        public IActionResult ProductionpickingEdit(int id)
        {
            ViewBag.Id = id;
            return View();
        }

        /// <summary>
        /// 根据ID获取生产领料单详情
        /// </summary>
        /// <param name="id">领料单ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetProductionPickingById(int id)
        {
            try
            {
                var result = await _productionpickingService.GetProductionPickingByIdAsync(id);
                if (result != null)
                {
                    return Json(new { success = true, data = result, message = "获取数据成功" });
                }
                else
                {
                    return Json(new { success = false, message = "未找到指定的领料单" });
                }
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = "获取数据失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 添加生产领料单
        /// </summary>
        /// <param name="dto">生产领料DTO</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddProductionPicking([FromBody] ProductionpickingDTO dto)
        {
            try
            {
                var result = await _productionpickingService.AddProductionPickingAsync(dto);
                if (result > 0)
                {
                    return Json(new { success = true, message = "添加成功", data = result });
                }
                else
                {
                    return Json(new { success = false, message = "添加失败" });
                }
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = "添加失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取所有生产领料单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetAllProductionPicking(string? code = null, string? issuanceOrderName = null, string? issuanceWarehouse = null, DateTime? issuanceDate = null, string documentStatus = "", int page = 1, int limit = 10)
        {
            try
            {
                var result = await _productionpickingService.GetAllProductionPickingAsync(code, issuanceOrderName, issuanceWarehouse, issuanceDate, documentStatus, page, limit);
                
                // 确保返回正确的分页数据格式
                var response = new { 
                    success = true, 
                    data = result.ListDate ?? new List<ProductionpickingModel>(), 
                    total = result.PageCount, // APIPaging中使用的是PageCount作为总记录数
                    page = result.PageIndex,
                    limit = limit,
                    message = "获取数据成功"
                };
                
                return Ok(response); // 使用Ok()确保返回200状态码
            }
            catch (System.Exception ex)
            {
                var errorResponse = new { 
                    success = false, 
                    message = "获取数据失败：" + ex.Message, 
                    data = new List<ProductionpickingModel>(), 
                    total = 0 
                };
                
                return Ok(errorResponse); // 即使出错也返回200状态码，由前端parseData处理
            }
        }

        /// <summary>
        /// 执行开票 - 更新单据状态为已完成
        /// </summary>
        /// <param name="id">领料单ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ExecuteInvoice(int id)
        {
            try
            {
                var result = await _productionpickingService.ExecuteInvoiceAsync(id);
                if (result)
                {
                    return Json(new { success = true, message = "开票成功，单据状态已更新为已完成" });
                }
                else
                {
                    return Json(new { success = false, message = "开票失败，未找到指定的领料单" });
                }
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = "开票失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 修改生产领料单
        /// </summary>
        /// <param name="updateData">修改数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdateProductionPicking([FromBody] System.Text.Json.JsonElement updateData)
        {
            try
            {
                // 安全地解析JSON数据
                if (!updateData.TryGetProperty("id", out var idElement) || !idElement.TryGetInt32(out int id))
                {
                    return Json(new { success = false, message = "缺少或无效的ID字段" });
                }

                if (id <= 0)
                {
                    return Json(new { success = false, message = "无效的ID：" + id });
                }

                // 安全地获取其他字段
                string issuanceOrderCode = GetStringProperty(updateData, "issuanceOrderCode") ?? "";
                string issuanceOrderName = GetStringProperty(updateData, "issuanceOrderName") ?? "";
                string issuanceDateStr = GetStringProperty(updateData, "issuanceDate") ?? "";
                string issuanceWarehouse = GetStringProperty(updateData, "issuanceWarehouse") ?? "";
                string productionWorkOrder = GetStringProperty(updateData, "productionWorkOrder") ?? "";
                string documentstatus = GetStringProperty(updateData, "documentstatus") ?? "草稿";
                string customerCode = GetStringProperty(updateData, "customerCode") ?? "";
                string customerName = GetStringProperty(updateData, "customerName") ?? "";
                string productionTask = GetStringProperty(updateData, "productionTask") ?? "";
                string taskName = GetStringProperty(updateData, "taskName") ?? "";
                string workstation = GetStringProperty(updateData, "workstation") ?? "";
                string remark = GetStringProperty(updateData, "remark") ?? "";

                // 验证必填字段
                if (string.IsNullOrEmpty(issuanceOrderCode))
                {
                    return Json(new { success = false, message = "领料单编号不能为空" });
                }
                if (string.IsNullOrEmpty(issuanceOrderName))
                {
                    return Json(new { success = false, message = "领料单名称不能为空" });
                }

                // 解析日期
                DateTime issuanceDate;
                if (!DateTime.TryParse(issuanceDateStr, out issuanceDate))
                {
                    return Json(new { success = false, message = "无效的日期格式：" + issuanceDateStr });
                }

                // 构造DTO
                var dto = new ProductionpickingDTO
                {
                    Id = id,
                    IssuanceOrderCode = issuanceOrderCode,
                    IssuanceOrderName = issuanceOrderName,
                    IssuanceDate = issuanceDate,
                    IssuanceWarehouse = issuanceWarehouse,
                    ProductionWorkOrder = productionWorkOrder,
                    Documentstatus = documentstatus,
                    CustomerCode = customerCode,
                    CustomerName = customerName,
                    ProductionTask = productionTask,
                    TaskName = taskName,
                    Workstation = workstation,
                    Remark = remark
                };

                var result = await _productionpickingService.UpdateProductionPickingAsync(dto);
                if (result)
                {
                    return Json(new { success = true, message = "修改成功" });
                }
                else
                {
                    return Json(new { success = false, message = "修改失败，未找到指定的领料单，ID：" + id });
                }
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = "修改失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 删除生产领料单
        /// </summary>
        /// <param name="id">领料单ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DeleteProductionPicking(int id)
        {
            try
            {
                if (id <= 0)
                {
                    return Json(new { success = false, message = "无效的ID：" + id });
                }

                var result = await _productionpickingService.DeleteProductionPickingAsync(id);
                if (result)
                {
                    return Json(new { success = true, message = "删除成功" });
                }
                else
                {
                    return Json(new { success = false, message = "删除失败，未找到指定的领料单" });
                }
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = "删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 安全地从JsonElement中获取字符串属性
        /// </summary>
        /// <param name="element">JSON元素</param>
        /// <param name="propertyName">属性名</param>
        /// <returns>属性值或null</returns>
        private string GetStringProperty(System.Text.Json.JsonElement element, string propertyName)
        {
            if (element.TryGetProperty(propertyName, out var property))
            {
                return property.GetString();
            }
            return null;
        }

    }
}
